package com.wangan.wanganpush.config;

import com.wangan.wanganpush.dao.ParamDao;
import com.wangan.wanganpush.model.Parameter;
import com.wangan.wanganpush.utils.AtomicValue;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.Signal;
import sun.misc.SignalHandler;

import java.util.List;
import java.util.Observable;
import java.util.Observer;


@Service
public class SignalMonitoringConfig  implements Observer {

    @Autowired
    AtomicValue atomicValue;

    @Autowired
    ParamDao paramDao;

    private static Logger logger = LogManager.getLogger(SignalMonitoringConfig.class);
    public void go(SignalMonitoringConfig signalMonitoringConfig){
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        HandlerTest sh = new HandlerTest();
                        sh.addObserver(signalMonitoringConfig);
                        sh.handleSignal("TERM");
                        System.out.println("Sleeping for 6 seconds: hit me with signals!");
                        Thread.sleep(6000);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
            }).start();

        } catch (Throwable x) {

            logger.error(x.getMessage(),x);
        }
    }


    @Override
    public void update(Observable arg0, Object arg1) {
        System.out.println("Received signal:" + arg1);
        try {
            //将序列信号值存数据库
            List<Parameter> all = paramDao.findAll();
            if(all != null && all.size()>0){
                all.get(0).setSeqNum(atomicValue.getAtuo());
                paramDao.save(all.get(0));
            }else {
                Parameter p = new Parameter();
                p.setSeqNum(atomicValue.getAtuo());
                paramDao.save(p);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);

    }
}


class HandlerTest extends  Observable implements SignalHandler {


    @Override
    public void handle(Signal signal) {
        setChanged();
        notifyObservers(signal);
    }



    /**
     *
     * @param signalName
     * @throws IllegalArgumentException
     */
    public void handleSignal(String signalName) throws IllegalArgumentException {


        try {

            Signal.handle(new Signal(signalName), this);

        } catch (IllegalArgumentException x) {

            throw x;

        } catch (Throwable x) {

            throw new IllegalArgumentException("Signal unsupported: "+signalName, x);
        }
    }

}